/* Copyright 2015 Esri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.example.zhengchaojun.arcgis.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import com.esri.arcgisruntime.mapping.view.MapRotationChangedEvent;
import com.esri.arcgisruntime.mapping.view.MapRotationChangedListener;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.example.zhengchaojun.arcgis.R;

/**
 * 类描述：罗盘:地图旋转控制组件，当地图旋转时显示
 * 作者：郑朝军 on 2018/5/10
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 * 修改人：郑朝军 on 2018/5/10
 * 修改备注：
 */
public class Compass extends View
{
    private float mAngle = 0;
    private Paint mPaint;
    private Bitmap mBitmap;
    private Matrix mMatrix;

    private MapView mMapView;

    public Compass(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        this.setVisibility(GONE);//默认不显示

        mPaint = new Paint();
        mMatrix = new Matrix();
        mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.map_compass);
    }

    public Compass(Context context, AttributeSet attrs, MapView mapView)
    {
        this(context, attrs);

        this.setVisibility(GONE);//默认不显示
        mMapView = mapView;
        if (mMapView != null)
        {
            mMapView.addMapRotationChangedListener(new MapRotationChangedListener()
            {
                @Override
                public void mapRotationChanged(MapRotationChangedEvent mapRotationChangedEvent)
                {
                    setRotationAngle(mMapView.getMapRotation());
                }
            });
        }
    }

    /**
     * 只要一旋转就显示出来
     *
     * @param angle 旋转角度
     */
    public void setRotationAngle(double angle)
    {
        mAngle = (float) angle;
        this.setVisibility(VISIBLE);
        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        mMatrix.reset();
        mMatrix.postRotate(-this.mAngle, mBitmap.getHeight() / 2, mBitmap.getWidth() / 2);
        canvas.drawBitmap(mBitmap, mMatrix, mPaint);
        super.onDraw(canvas);
    }
}
